package com.diao.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author: chenzhidiao
 * @date: 2021/4/18 12:13
 * @description:
 * @version: 1.0
 */
public class NettyClient {
    public void run() throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();

        try {


            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });

            System.out.println("...客户端准备完毕...");

            //启动客户端去连接服务端
            ChannelFuture channelFuture = bootstrap.connect("localhost", 9000).sync();
            //给关闭通道进行监听
            channelFuture.channel().closeFuture().sync();

        } finally {
            eventExecutors.shutdownGracefully();
        }


    }

    public static void main(String[] args) throws InterruptedException {
        new NettyClient().run();
    }
}
